<template>
  <div>
    <el-table-form ref="form" class="form" :model="query">
      <el-form-item :table-form-merge="2" label="缴存日期:">
        <el-date-picker
          v-model="query.date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
          :clearable="false"
        />
      </el-form-item>
      <el-form-item label="所属机构:" prop="orgSNNo">
        <el-tree-select
          v-model="query.orgSNNo"
          :clearable="true"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props: {
              value: 'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData,
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item label="单据状态:" prop="subjectFlag">
        <el-select v-model="query.billStatus" clearable>
          <el-option
            v-for="(l, i) in billStatusList"
            :key="i"
            :label="l.desc"
            :value="l.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="缴存类型:" prop="subjectFlag">
        <el-select v-model="query.handInType" clearable>
          <el-option
            v-for="(l, i) in handInTypeList"
            :key="i"
            :label="l.desc"
            :value="l.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="缴存项:" prop="subjectFlag">
        <el-select v-model="query.handInItem" clearable>
          <el-option
            v-for="(l, i) in handInItemList"
            :key="i"
            :label="l.text"
            :value="l.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="银行账号:" prop="subjectFlag">
        <el-select v-model="query.cardNo" clearable>
          <el-option
            v-for="(l, i) in bankList"
            :key="i"
            :label="`${l.cardNo} ${l.accountName}`"
            :value="l.cardNo"
          />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button
          v-permission="1"
          type="primary"
          icon="el-icon-search"
          @click="fetchData({})"
        >查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button
          v-permission="2"
          type="primary"
          icon="el-icon-folder-add"
          @click="add"
        >新增</el-button>
        <el-button
          type="primary"
          icon="el-icon-download"
          :loading="$loadingPlugin.exportFile"
          @click="exportFile"
        >导出</el-button>
        <!-- <el-button type="primary" icon="" :loading="$loadingPlugin.openSetting" @click="openSetting">资金科目匹配</el-button> -->
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      v-loading="$loadingPlugin.fetchData"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @sort-change="sortChange"
      @fetch="fetchData"
    />
    <!-- bankList       -->
    <add
      ref="add"
      :tree-data="treeData"
      :bill-status-list="billStatusList"
      :hand-in-type-list="handInTypeList"
      :org-list="orgList"
      :bank-list="bankList"
      @refresh="refresh"
    />
    <!-- <match ref="match" @refresh="refresh" /> -->
  </div>
</template>

<script>
  import {
    handindayrecordSearch,
    handindayrecordSearchEnum,
    queryMap,
    handindayrecordAudit,
    handindayrecordExport
  } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import { parseTime, formatColumnMap } from '@/utils'
  import moment from 'dayjs'
  export default {
    name: 'storeDeposit',
    components: {
      add: require('./components/add.vue').default
    // match: require('./components/match.vue').default
    },

    data() {
      return {
        actionColWidth: 80,
        handInItemList: [], // 本地
        bankList: [],
        billStatusList: [],
        handInTypeList: [],
        query: {
          billStatus: null,
          handInType: null,
          handInItem: null,
          cardNo: null,
          date: [
            new Date().setDate(
              new Date().getDate() - 1 < 0 ? '' : new Date().getDate() - 1
            ),
            new Date()
          ], // 简易版昨天到今天
          handInTime_Order: '',
          orgName_Order: ''
        },

        searchParams: {},
        tableData: {
          total: 0,
          data: []
        }
      }
    },
    computed: {
      ...mapGetters(['orgList', 'exportDomain']),
      column: function() {
        return [
          {
            type: 'index'
          },
          { label: '单据编号', prop: 'billCode', width: 220 },
          {
            label: '缴存门店',
            prop: 'orgName',
            width: 150,
            sortable: 'custom'
          },
          {
            label: '银行账号',
            prop: 'cardNo',
            width: 250,
            render: (h, { row }) => (
              <span>{row.cardNo && `${row.cardNo} ${row.accountName}`}</span>
            )
          },
          // { label: '账户名', prop: 'accountName', width: 200, align: 'center', hidden: true },
          { label: '缴存人', prop: 'operator', width: 100 },
          {
            label: '缴存类型',
            prop: 'handInType',
            width: 100,
            render: (h, { row }) => (
              <span>
                {row.handInType &&
                formatColumnMap(this.handInTypeList, 'value', row.handInType, 'desc')}
              </span>
            )
          },
          {
            label: '缴存项',
            prop: 'handInItem',
            width: 100,
            render: (h, { row }) => (
              <span>{row.handInItem && this.handInItemformatter(row.handInItem)}</span>
            )
          },
          { label: '金额', prop: 'amount', width: 100, align: 'right' },
          {
            label: '缴存时间',
            prop: 'handInTime',
            width: 180,
            sortable: 'custom',
            render: (h, { row }) => (
              <span>
                {row.handInTime && parseTime(row.handInTime, '{y}-{m}-{d}  {h}:{i}:{m} ')}
              </span>
            )
          },
          { label: '备注', prop: 'remark', width: 200 },
          {
            label: '单据状态',
            prop: 'billStatus',
            width: 100,
            render: (h, { row }) => (
              <span>
                {row.billStatus &&
                this.billStatusList.find((l) => l.value === row.billStatus)
                  ? this.billStatusList.find((l) => l.value === row.billStatus).desc
                  : ''}
              </span>
            )
          },
          { label: '确认人',
            prop: 'auditor',
            width: 100,
            render: (h, { row }) => {
              return (
                <span>
                  { row.billStatus !== 1 ? row.auditor : ''}
                </span>
              )
            }
          },
          {
            label: '确认时间',
            prop: 'auditTime',
            width: 180,
            render: (h, { row }) => (
              <span>
                { row.billStatus !== 1 ? row.auditTime && parseTime(row.auditTime, '{y}-{m}-{d}  {h}:{i}:{m} ') : ''}
              </span>
            )
          },
          {
            label: '操作',
            fixed: 'right',
            className: 'action-col',
            width: this.actionColWidth,
            render: (h, { row, $index }) => {
              return (
                <div>
                  {row.billStatus === 1 && (
                    <el-link
                      v-permission='4'
                      underline={false}
                      size='mini'
                      onClick={() => this.audit(row, 2)}
                    >
                      {' '}
                      审核{' '}
                    </el-link>
                  )}
                  {row.billStatus === 2 && (
                    <el-link
                      v-permission='5'
                      underline={false}
                      size='mini'
                      onClick={() => this.audit(row, 1)}
                    >
                      {' '}
                      反审核{' '}
                    </el-link>
                  )}

                  {row.billStatus === 1 && (
                    <el-link
                      v-permission='3'
                      underline={false}
                      size='mini'
                      onClick={() => this.editRow(row, $index)}
                    >
                      编辑
                    </el-link>
                  )}
                  {row.billStatus === 1 && (
                    <el-link
                      v-permission='6'
                      underline={false}
                      type='danger'
                      size='mini'
                      onClick={() => this.audit(row, 3)}
                    >
                      作废{' '}
                    </el-link>
                  )}
                </div>
              )
            }
          }
        ]
      }
    },
    async created() {
      await this.getTreeData()
      await this.getEnum()
    },
    mounted() {
      this.$watch('query.handInType', (n) => {
        var datas = []
        if (n === 1) {
          datas.push({ text: '其他收入', value: 17 })
          datas.push({ text: '配件收入', value: 20 })
          datas.push({ text: '以前月结收回', value: 21 })
          datas.push({ text: '调整收入', value: 22 })
          datas.push({ text: '过户', value: 25 })
          datas.push({ text: '补卡', value: 26 })
        } else if (n === 2) {
          datas.push({ text: '交款', value: 204 })
          datas.push({ text: '费用支出', value: 205 })
          datas.push({ text: '现金券', value: 206 })
          datas.push({ text: '调整支出', value: 208 })
        } else {
          datas = []
        }
        this.handInItemList = datas
      })
    },
    methods: {
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map((item) => ({
          label: item.orgName,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.orgSNNo = value.orgSNNo
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      sortChange(val) {
        // var param
        // console.log(val)
        if (val.prop === 'orgName') {
          var str = 'orgName_Order'
          var value = ''
          switch (val.order) {
          case 'ascending':
            value = 'asc'
            break
          case 'descending':
            value = 'desc'
            break
          default:
            value = ''
          }
          this.query[str] = value
        } else if (val.prop === 'handInTime') {
          str = 'handInTime_Order'
          value = ''
          switch (val.order) {
          case 'ascending':
            value = 'asc'
            break
          case 'descending':
            value = 'desc'
            break
          default:
            value = ''
          }
          this.query[str] = value
        }
        this.fetchData({})
      // console.log(this.query)
      // console.log(val)
      },
      async fetchData({ currentPage = 1, pageSize = 20 }) {
        const params = {
          ...this.query,
          currentPage,
          pageSize
        }
        if (this.query.date) {
          params['startTime'] = this.query.date[0]
          params['endTime'] = this.query.date[1]
          const diff = moment(this.query.date[1]).diff(moment(this.query.date[0]), 'days')
          if (diff > 366) {
            this.$message.error('查询日期最大支持查询1年')
            return
          }
        }
        const res = await handindayrecordSearch(params)
        this.searchParams = params
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      editRow(row) {
        this.$refs.add.open(row)
      },
      async delRow(row) {
        this.$confirm('确认删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
        // const params = {
        //   orgId: row.orgId,
        //   // startDt: new Date(row.startDt)
        //   startDt: parseTime(row.startDt, '{y}-{m}-{d} {h}:{i}:{m}')
        // }
        // const res = await initialaccountDelete(params)
        // if (res.success) {
        //   this.refresh()
        // }
        })
      },
      add() {
        this.$refs.add.open()
      },
      openSetting() {
        this.$refs.match.open()
      },
      async audit(row, num) {
        this.$confirm('确认要进行操作吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          const params = {
            billCode: row.billCode,
            billStatus: num
          }
          const res = await handindayrecordAudit(params)
          if (res.success) {
            this.fetchData({})
          }
        })
      },
      refresh() {
        this.fetchData({})
      },
      async getEnum() {
        const res = await handindayrecordSearchEnum()
        this.bankList = res.data
        const res1 = await queryMap({ enumName: 'HandInStatus' })
        this.billStatusList = res1.data
        const res2 = await queryMap({ enumName: 'BalanceType' })
        this.handInTypeList = res2.data
      },
      handInItemformatter(v, column) {
        if (v * 1 === 17) {
          return '其他收入'
        } else if (v * 1 === 20) {
          return '配件收入'
        } else if (v * 1 === 21) {
          return '以前月结收回'
        } else if (v * 1 === 22) {
          return '调整收入'
        } else if (v * 1 === 25) {
          return '过户'
        } else if (v * 1 === 26) {
          return '补卡'
        } else if (v * 1 === 204) {
          return '交款'
        } else if (v * 1 === 205) {
          return '费用支出'
        } else if (v * 1 === 206) {
          return '现金券'
        } else if (v * 1 === 208) {
          return '调整支出'
        }
        return ''
      },
      async exportFile() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.column))
          copyColumn.pop()
          const str = {}
          copyColumn.forEach((item) => {
            str[item.prop] = item.label
          })
          handindayrecordExport({
            paramInfo: _this._getQuery(_this.searchParams),
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach((it) => {
                width += it.offsetWidth + 10
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      }
    }
  }
</script>

<style lang="scss" scoped></style>
